package com.example.snakegame
import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.view.View
import android.widget.AdapterView
import android.widget.ArrayAdapter
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import androidx.databinding.DataBindingUtil
import com.example.snakegame.R
import com.example.snakegame.databinding.ActivityGameBinding
import com.example.snakegame.model.Score
import com.example.snakegame.utils.SharedPreferencesManager
import com.example.snakegame.view.SnakeView

class GameActivity : AppCompatActivity() {
    companion object {
        private const val TAG = "GameActivity"
    }

    private lateinit var binding: ActivityGameBinding
    private lateinit var snakeView: SnakeView
    private lateinit var prefsManager: SharedPreferencesManager
    private lateinit var username: String
    private var gameThread: Thread? = null
    private var currentSpeed = 100L
    private var currentScore = 0
    private var isPaused = false

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        Log.d(TAG, "onCreate: Starting game activity")
        
        binding = DataBindingUtil.setContentView(this, R.layout.activity_game)
        binding.lifecycleOwner = this
        binding.activity = this

        username = intent.getStringExtra("username") ?: run {
            Log.e(TAG, "onCreate: Username is null")
            finish()
            return
        }
        
        Log.d(TAG, "onCreate: Username: $username")
        
        prefsManager = SharedPreferencesManager(this)
        snakeView = binding.snakeView
        
        setupGameCallbacks()
        setupControls()
        setupDifficultySpinner()
        startGameLoop()
    }

    private fun setupGameCallbacks() {
        snakeView.onScoreChanged = { score ->
            Log.d(TAG, "Score changed: $score")
            currentScore = score
            binding.invalidateAll()
        }
        
        snakeView.onGameOver = { score ->
            Log.d(TAG, "Game over with score: $score")
            handleGameOver(score)
        }
    }

    private fun setupControls() {
        binding.apply {
            upButton.setOnClickListener { snakeView.setDirection(SnakeView.Direction.UP) }
            downButton.setOnClickListener { snakeView.setDirection(SnakeView.Direction.DOWN) }
            leftButton.setOnClickListener { snakeView.setDirection(SnakeView.Direction.LEFT) }
            rightButton.setOnClickListener { snakeView.setDirection(SnakeView.Direction.RIGHT) }
            pauseButton.setOnClickListener {
                snakeView.togglePause()
                isPaused = !isPaused
                invalidateAll()
            }
        }
    }

    private fun setupDifficultySpinner() {
        val difficulties = arrayOf("简单", "中等", "困难")
        val adapter = ArrayAdapter(this, android.R.layout.simple_spinner_item, difficulties)
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
        
        binding.difficultySpinner.adapter = adapter
        binding.difficultySpinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
            override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
                currentSpeed = when (position) {
                    0 -> 2000L // 简单
                    1 -> 1500L // 中等
                    2 -> 1000L // 困难
                    else -> 150L
                }
                restartGameLoop()
            }
            
            override fun onNothingSelected(parent: AdapterView<*>?) {}
        }
    }

    private fun restartGameLoop() {
        gameThread?.interrupt()
        startGameLoop()
    }

    private fun startGameLoop() {
        gameThread = Thread {
            while (!Thread.interrupted()) {
                snakeView.updateGame()
                try {
                    Thread.sleep(currentSpeed)
                }catch (e:Exception){
                    Log.e(TAG, "Error updating game", e)
                }
            }
        }.apply { start() }
    }

    override fun onDestroy() {
        super.onDestroy()
        gameThread?.interrupt()
        snakeView.releaseSoundManager()
    }

    private fun handleGameOver(finalScore: Int) {
        Log.d(TAG, "Handling game over. Final score: $finalScore")
        runOnUiThread {
            try {
                val score = Score(username, finalScore)
                prefsManager.saveScore(score)
                
                AlertDialog.Builder(this)
                    .setTitle("游戏结束")
                    .setMessage("得分：$finalScore")
                    .setPositiveButton("查看排行榜") { _, _ ->
                        startActivity(Intent(this, LeaderboardActivity::class.java))
                        finish()
                    }
                    .setNegativeButton("重新开始") { _, _ ->
                        recreate()
                    }
                    .setCancelable(false)
                    .show()
            } catch (e: Exception) {
                Log.e(TAG, "Error handling game over", e)
            }
        }
    }

    val gameScore: Int
        get() = currentScore

    val gamePaused: Boolean
        get() = isPaused
} 